package com.kgc.mall.service;

import com.kgc.mall.mapper.UserMapper;
import com.kgc.mall.pojo.User;
import com.kgc.mall.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;


import java.util.ArrayList;
import java.util.List;

public class UserServiceImpl implements UserService{

  @Override
  public List<User> getUserInfoByPage(String loginName, String userName, int pageNum, int pageSize) {
    UserMapper userMapper = MyBatisUtil.getMapper(UserMapper.class);
    List<User> userList = new ArrayList<>();
    SqlSession session = MyBatisUtil.newSession();
    int statrtNo = 0;
    try {
      statrtNo = (pageNum-1)*pageSize;
      userList = userMapper.getUsersByPaging(statrtNo,pageSize,loginName,userName);
    } catch (Exception e) {
     throw e;
    }finally {
      MyBatisUtil.closeSession();
    }
    return userList;
  }

  @Override
  public int addUserInfo(User user) {
    UserMapper userMapper = MyBatisUtil.getMapper(UserMapper.class);
    return userMapper.insertUser(user);
  }

  @Override
  public int updateUserInfo(User user) {
    UserMapper userMapper = MyBatisUtil.getMapper(UserMapper.class);
    return userMapper.updateUser(user);
  }

  @Override
  public User getUserInfo(int userId) {
    UserMapper userMapper = MyBatisUtil.getMapper(UserMapper.class);
    return userMapper.getUser(userId);
  }

  @Override
  /**
   * 删除用户
   */
  public int deleteUserByUid(int userId) {
    UserMapper userMapper = MyBatisUtil.getMapper(UserMapper.class);
    return userMapper.deleteUser(userId);
  }

  @Override
  public List<User>  getUser(String loginName, String userName) {
    UserMapper userMapper = MyBatisUtil.getMapper(UserMapper.class);
      List<User> search = new ArrayList<>();
    try {
      SqlSession session = MyBatisUtil.newSession();
      search = userMapper.getUserIn(loginName, userName);
    } catch (Exception e) {
      throw e;
    }finally {
      MyBatisUtil.closeSession();
    }
    return search;
  }

  @Override
  public List<User> getUserInfoByPre(String loginName, String userName, int pageNum, int pageSize) {
    UserMapper userMapper = MyBatisUtil.getMapper(UserMapper.class);
    List<User> userList = new ArrayList<>();
    SqlSession session = MyBatisUtil.newSession();
    int statrtNo = 0;
    try {
      statrtNo = (pageNum-1)*pageSize;
      if (statrtNo<0){
        statrtNo = 0;
      }
      userList = userMapper.getUsersByPaging(statrtNo,pageSize,loginName,userName);
    } catch (Exception e) {
      throw e;
    }finally {
      MyBatisUtil.closeSession();
    }
    return userList;
  }

  @Override
  public long getCount(){
    UserMapper userMapper = MyBatisUtil.getMapper(UserMapper.class);
    long count = 0;
    SqlSession session = MyBatisUtil.newSession();
    try {
      count = userMapper.getCount()/10;
    } catch (Exception e) {
      throw e;
    }finally {
      MyBatisUtil.closeSession();
    }
    return count;
  }


}
